package com.mxl;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

public class ShiroIniApplication {
    public static void main(String[] args) {
        //通过shiro.ini创建SecurityManager
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //将SecurityManager设置成单例模式
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        //Subject即当前的用户对象
        Subject curUser = SecurityUtils.getSubject();
        System.out.println("curUser: " + JSON.toJSONString(curUser));
        //获取Session
        Session session = curUser.getSession();
        //给session设置属性值
        session.setAttribute("key", "value");
        //获取session中的属性值
        String value = (String)session.getAttribute("key");
        System.out.println("value: " + value);


        //登录
        //isAuthenticated方法用来判断当前用户是否已经登录,false: 代表当前用户未登录
        if(!curUser.isAuthenticated()){
            System.out.println("开始登录...........");
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("sang","123" );
            //登录
            try {
                curUser.login(usernamePasswordToken);
                System.out.println("登录成功, 当前用户名: " + curUser.getPrincipal());
                System.out.println("登录后的curUser: " + JSON.toJSONString(curUser));


                //TODO 这里为空????  why?
                //判断是否具有admin角色
                if(curUser.hasRole("admin")){
                    System.out.println("具有admin角色!");
                }else{
                    System.out.println("没有admin角色!");
                }

                //判断是否具有某权限
                if(curUser.isPermitted("\"lightsaber:wield\"")){
                    System.out.println("有权限!");
                }else{
                    System.out.println("无权限!");
                }


                System.out.println("开始注销登录.......");
                curUser.logout();
                System.out.println("注销登录后的用户信息: " + JSON.toJSONString(curUser));
            }catch (IncorrectCredentialsException e){
                System.out.println("密码不正确!");
            }catch (UnknownAccountException e){
                System.out.println("用户名不正确!");
            }catch(LockedAccountException e){
                System.out.println("账户被禁用!!");
            }catch (AuthenticationException e){
                System.out.println("未知异常!" + e.getMessage());
            }

        }
    }
}
